import React, { useCallback, useRef, useState } from 'react';
import { Button, Drawer, Form, Input, InputNumber, message, Popconfirm, Select, Space, Switch } from 'antd';
import { ProTable, ProColumns, FooterToolbar } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { fetchSupportList, deleteSupport, createSupport, updateSupport, prOnOff } from '@/services/ant-design-pro/support';
import type { ActionType } from '@ant-design/pro-components';
import FileaUpload from '@/components/FileUpload_name';

const { Option } = Select;

const SupportList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [form] = Form.useForm();
  const [activeKey, setActiveKey] = useState<string>('0');
  const { run: delRun, loading: deleteLoading } = useRequest(deleteSupport, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('删除成功');
    },
    onError: () => {
      message.error('删除失败，请重试');
    },
  });

  const handleRemove = useCallback(
    async (selectedRows: any[]) => {
      if (selectedRows.length === 0) {
        message.warning('请先选择要删除的项');
        return;
      }
      await delRun({ id: selectedRows.map((row) => row.id)[0] });
    },
    [delRun],
  );

  const columns: ProColumns<any>[] = [
    {
      title: '问题名称',
      dataIndex: 'questionName',
      width: 200,
      ellipsis: true,
      hideInTable: activeKey === '1',
      render: (text, record) => (
        <a onClick={() => {
          setCurrentRecord(record);
          form.setFieldsValue(record);
          setDrawerVisible(true);
        }}>{text}</a>
      ),
    },
    {
      title: '文档名称',
      dataIndex: 'documentName',
      hideInTable: activeKey !== '1',
    },
    {
      title: '文档链接',
      dataIndex: 'documentUrl',
      search: false,
      ellipsis: true,
      hideInTable: activeKey !== '1',
    },
    {
      hidden: true,
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        0: { text: '数据API技术相关' },
        1: { text: 'API接口文档相关' },
        2: { text: '售后及商务问题模板' },
      },
      search: false,
      width: 150,
    },
    {
      title: '启用/禁用',
      valueEnum: {
        0: { text: '启用' },
        1: { text: '禁用' },
      },
      search: false,
      width: 100,
      dataIndex: 'prOnoff',
      render: (text, record) => (
        <Switch
          checked={record.prOnoff === '1'}
          onChange={(checked) => handleToggleEnable(record.id, checked)}
        />
      ),
    },
    {
      width: 100,
      title: '排序',
      dataIndex:'sort',
      search: false
    },
    {
      title: '操作',
      width: 120,
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            form.setFieldsValue(record);
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          title="确定删除吗？"
          onConfirm={() => handleRemove([record])}
          okText="确定"
          cancelText="取消"
        >
          <a key="delete">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const handleToggleEnable = async (id: number, enabled: boolean) => {
    try {
      await prOnOff({ id, prOnOff: enabled ? 1 : 0 });
      actionRef.current?.reload();
      message.success(enabled ? '启用成功' : '禁用成功');
    } catch (error) {
      message.error(enabled ? '启用失败' : '禁用失败');
    }
  };

  return (
    <>
      <ProTable<any>
        headerTitle="支持与帮助列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            key={'new'}
            type="primary"
            onClick={() => {
              setCurrentRecord(undefined);
              form.resetFields();
              setDrawerVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              {
                key: '0',
                label: <span>数据API技术相关</span>,
              },
              {
                key: '2',
                label: <span>售后及商务问题模板</span>,
              },
              {
                key: '1',
                label: <span>API接口文档相关</span>,
              },
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
        request={(params) => fetchSupportList({ ...params, type: activeKey })}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     // Implement row selection if needed
        //   },
        // }}
      />

      <Drawer
        title={currentRecord ? ('编辑' + (activeKey === '1' ? '数据API技术相关' : activeKey === '2' ? 'API接口文档相关' : '售后及商务问题模板')) : ('新建' + (activeKey === '1' ? '数据API技术相关' : activeKey === '2' ? 'API接口文档相关' : '售后及商务问题模板'))}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>取消</Button>
            <Button
              type="primary"
              onClick={() => {
                form.validateFields().then(async (values) => {
                  if (currentRecord) {
                    await updateSupport({ ...currentRecord, ...values ,prOnoff: values.prOnoff  ? 1 : 0 });
                  } else {
                    await createSupport({ ...values, prOnoff: values.prOnoff  ? 1 : 0 , type: activeKey });
                  }
                  setDrawerVisible(false);
                  actionRef.current?.reload();
                });
              }}
            >
              提交
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
        {activeKey !== '1' && (
          <><Form.Item
              name="questionName"
              label="问题名称"
              rules={[{ required: true, message: '请输入问题名称' }]}
            >
              <Input placeholder="请输入问题名称" />
            </Form.Item><Form.Item name="answer" label="答案">
                <Input.TextArea />
              </Form.Item></>
        )}
          {activeKey === '1' && (
            <>
              <Form.Item
                name="documentName"
                label="文档名称"
              >
                <Input placeholder="请输入文档名称" />
              </Form.Item>
              <Form.Item name="documentUrl" label="上传文件">
                <FileaUpload value={form.getFieldValue('documentUrl')} onChange={(url) => form.setFieldsValue({ documentUrl: url })} />
              </Form.Item>
            </>
          )}
          <Form.Item hidden={true}
            name="type"
            label="类型"
          >
            <Select placeholder="请选择类型">
              <Option value="0">数据API技术相关</Option>
              <Option value="2">售后及商务问题模板</Option>
              <Option value="1">API接口文档相关</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="sort"
            label="排序"
          >
            <Input type='number'></Input>
          </Form.Item>
          {/* <Form.Item
            name="prOnoff"
            label="启用/禁用"
            valuePropName="checked"
          >
            <Switch checked={form.getFieldValue('prOnoff')} />
          </Form.Item> */}
        </Form>
      </Drawer>
    </>
  );
};

export default SupportList;